package edu.scut.yi.yx.processer;

import java.sql.SQLException;

import com.electrotank.electroserver5.extensions.api.PluginApi;
import com.electrotank.electroserver5.extensions.api.value.EsObject;
import com.electrotank.electroserver5.extensions.api.value.EsObjectRO;

import edu.scut.yi.yx.dbmanager.DatabaseJDBCPlugin;
import edu.scut.yi.yx.lobbymanager.Command;

public class GetUserInfoProcesser extends AbstractProcesser{

	private DatabaseJDBCPlugin databaseJDBCPlugin;
	private EsObject userInfoResponse;
	
	@Override
	public String getCommand() {
		// TODO Auto-generated method stub
		return Command.GetUserInfo.getCode();
	}

	@Override
	public void process(String user, EsObjectRO message, PluginApi api) {
		// TODO Auto-generated method stub
		databaseJDBCPlugin = (DatabaseJDBCPlugin)api.getServerPlugin("DatabaseJDBCPlugin");
		userInfoResponse = new EsObject();
		try{
			api.getLogger().debug("----userinforesponse-----username "+message.getString(Command.Message.getCode()));
			EsObject result = databaseJDBCPlugin.doQuery("SELECT * FROM userinfo WHERE username = "+"'"+message.getString(Command.Message.getCode())+"'");
			if(result == null){
				api.getLogger().debug("userinfo is empty");
				throw new IllegalStateException("load buddy list error");
			}
			
			api.getLogger().debug("----userinforesponse-----"+Command.Action.getCode()+" "+Command.GetUserInfo.getCode());
			api.getLogger().debug("----userinforesponse-----"+Command.Message.getCode()+" "+result);
			api.getLogger().debug("----userinforesponse-----"+Command.State.getCode()+" "+Command.Success.getCode());
			userInfoResponse.setString(Command.Action.getCode(), Command.GetUserInfo.getCode());
			userInfoResponse.setString(Command.State.getCode(), Command.Success.getCode());
			userInfoResponse.setEsObject(Command.Message.getCode(), result);
			
			//api.createOrUpdateUserVariable(user, "userinfo", result);
			//api.getLogger().debug(api.getUserVariable(user, "userinfo").getValue().toString());
			}catch(SQLException e){
				e.printStackTrace();
			}
			// MessagingHelper.sendSuccessMessage(Command.LoadBuddies, user, results, api);
			api.getLogger().debug("----send userinforesponse-----"+Command.Action.getCode()+" "+Command.GetUserInfo.getCode());
			api.sendPluginMessageToUser(user, userInfoResponse);
	}

}
